package com.tsxy.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tsxy.controller.dto.BookDto;
import com.tsxy.controller.dto.BookFileRela;
import com.tsxy.entity.Files;
import com.tsxy.entity.UsedBook;
import com.tsxy.mapper.FileMapper;
import com.tsxy.mapper.UsedBookMapper;
import com.tsxy.mapper.UsedBookPictureRelationMapper;
import com.tsxy.service.FilesService;
import com.tsxy.service.IUsedBookService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 飞
 * @since 2022-03-12
 */
@Service
public class UsedBookServiceImpl extends ServiceImpl<UsedBookMapper, UsedBook> implements IUsedBookService {
    @Autowired
    private UsedBookMapper bookMapper;
    @Autowired
    private UsedBookPictureRelationMapper bookPictureRelationMapper;
    @Autowired
    private FilesService filesService;

    @Override
    public List getAll(String name, String author, Integer pageNum, Integer pageSize) {
        Integer begin = (pageNum - 1) * pageSize;
        Integer size = pageSize;
        if ( !StrUtil.isBlank(name)){
            name = "%"+name+"%";
        }
        if ( !StrUtil.isBlank(author)){
            author = "%"+author+"%";
        }
        List<BookDto> bookDtos = bookMapper.getAll(name, author, begin, size);
        List<BookFileRela> bookFileRelas = bookPictureRelationMapper.selectAllRelation();
        Map<Integer, String> map = bookFileRelas.stream().collect(Collectors.toMap(BookFileRela::getBookId, BookFileRela::getFiles));
        bookDtos.forEach(e -> {
            if (map.get(e.getId()) != null){
                ArrayList<String> list = CollUtil.toList(map.get(e.getId()).split(","));
                List<Files> files = filesService.lambdaQuery().in(Files::getId, list).list();
                List<String> list1 = files.stream().map(Files::getUrl).collect(Collectors.toList());
                e.setFilesList(files);
                e.setFiles(list1);
            }
        });
        return bookDtos;
    }

    @Override
    public Integer cont() {
        return bookMapper.count();
    }
}
